package com.ruoyi.system.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.google.common.collect.Lists;
import com.ruoyi.common.utils.QiniuCloudUtil;
import com.ruoyi.system.domain.MaterialThree;
import com.ruoyi.system.domain.MaterialTwo;
import com.ruoyi.system.domain.PickCondition;
import com.ruoyi.system.service.IWatehouseMaterialService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 材料Service业务层处理
 *
 * @author ruoyi
 * @date 2020-12-16
 */
@Service
public class WatehouseMaterialServiceImpl implements IWatehouseMaterialService {
    @Resource
    private com.ruoyi.system.mapper.WatehouseMaterialMapper WatehouseMaterialMapper;

    @Resource
    private com.ruoyi.system.mapper.WarehouseDetailMapper WarehouseDetailMapper;

    /**
     * 查询材料明细记录列表
     *
     * @param material 材料
     * @return 材料
     */
    @Override
    public List<MaterialTwo> selectMaterialList(MaterialTwo material, Integer wid) {
        Double a = 0.0;
        HashMap<String, Object> map = new HashMap();
        map.put("material", material);
        map.put("wid", wid);
        //查寻和仓库有关的材料基本信息
        List<MaterialTwo> materials = WatehouseMaterialMapper.selectMaterialList(map);
        if (materials.size() > 0) {//判断是否有数据
            for (int i = 0; i < materials.size(); i++) {
                if (WatehouseMaterialMapper.selectMateerialcontent(materials.get(i).getmId(), wid) != null) {//查询当前材料库存
                    materials.get(i).setMdSum(WatehouseMaterialMapper.selectMateerialcontent(materials.get(i).getmId(), wid));
                    if(material.getiDate()!=null){
                        HashMap<String, Object> map2 = new HashMap();
                        map2.put("mid", materials.get(i).getmId());
                        map2.put("iDate", material.getiDate());
                        map2.put("wid", wid);
                        if (WatehouseMaterialMapper.selectinventorylList(map2)== null) {
                            materials.get(i).setiCount(a);
                        } else {
                            materials.get(i).setiCount(WatehouseMaterialMapper.selectinventorylList(map2).getiCount());
                        }
                    }else{
                        HashMap<String, Object> map2 = new HashMap();
                        map2.put("mid", materials.get(i).getmId());
                        map2.put("iDate", material.getiDate());
                        map2.put("wid", wid);
                        if (WatehouseMaterialMapper.selectinventorylList2(map2) == null) {
                            materials.get(i).setiCount(a);
                        } else {
                            materials.get(i).setiCount(WatehouseMaterialMapper.selectinventorylList2(map2).getiCount());
                        }
                    }
                    materials.get(i).setiDate(material.getiDate());
                }
            }
        }
        return materials;
    }

    @Override
    public List<MaterialTwo> selectWarehousematerialBywid(MaterialTwo materialTwo, long wid) {
        HashMap<String, Object> map = new HashMap();
        map.put("material", materialTwo);
        map.put("wid", wid);
        List<MaterialTwo> list = WatehouseMaterialMapper.selectWarehousematerialBywid(map);
        return list;
    }

    @Override
    public List<MaterialTwo> selectMaterialListall(MaterialTwo material) {
        HashMap<String, Object> map = new HashMap();
        map.put("material", material);
        List<MaterialTwo> list = WatehouseMaterialMapper.selectMaterialListall(map);
        return list;
    }

    @Override
    public MaterialTwo selectaterialByid(long mid) {
        return WatehouseMaterialMapper.selectaterialByid(mid);
    }

    @Override
    public int updateMaterial(MaterialTwo materialTwo, Long wid) {
        HashMap map = new HashMap();
        map.put("mName", materialTwo.getmName());
        map.put("mModel", materialTwo.getmModel());
        map.put("mId", materialTwo.getmId());
//     同名
        if (WatehouseMaterialMapper.selectMaterialCountByid(map) > 0) {
//            材料表中有这个材料
//           再去判断中间表中有没有关联
            MaterialThree materialThree = WatehouseMaterialMapper.selectMatByname(materialTwo.getmName(),materialTwo.getmModel());
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("mId", materialThree.getmId());
            hashMap.put("wId", wid);
            if (WatehouseMaterialMapper.selectMatAndWares(hashMap) != 1) {
                //插入
                return 1;

            }else{
                WatehouseMaterialMapper.insertMatAndWares(hashMap);
                return 2;
            }
        } else {
            WatehouseMaterialMapper.updateMaterial(materialTwo);
            return 2;
        }

    }

    //仓库材料新增
    @Override
    public int insertMaterial(MaterialThree material, long wid) {
        //查传过来的名字有没有；
        int result;
        MaterialThree materialThree1 = WatehouseMaterialMapper.selectMatByname(material.getmName(), material.getmModel());
        if (null == materialThree1) {
//            证明材料表中都没有这个材料
//            去材料表中添加新材料，并在关联表中插入新纪录
            WatehouseMaterialMapper.insertMaterial(material);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("mId", material.getmId());
            hashMap.put("wId", wid);
            WatehouseMaterialMapper.insertMatAndWares(hashMap);
            result = 100;
        } else {
//           材料表中有这个材料
//           再去判断中间表中有没有关联
            MaterialThree materialThree = WatehouseMaterialMapper.selectMatByname(material.getmName(),material.getmModel());
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("mId", materialThree.getmId());
            hashMap.put("wId", wid);
            if (WatehouseMaterialMapper.selectMatAndWares(hashMap) != 1) {
                //插入
                WatehouseMaterialMapper.insertMatAndWares(hashMap);
                result = 100;
            } else {
                //重名
                result = 200;
            }

        }
        return result;
    }

    //项目材料删除
    @Override
    public int deleteMaterialById(long wid, Long mId) {
        HashMap map = new HashMap();
        PickCondition pickCondition = new PickCondition();
        map.put("pickCondition",pickCondition);
        map.put("wid", wid);
        map.put("mid", mId);
        if (WarehouseDetailMapper.selectMaterialList(map).size() > 0) {
            return 0;
        } else {
            return WatehouseMaterialMapper.deleteMaterialWarehouseById(map);
        }
    }

    //返回所有单位
    @Override
    public List<String> reunits() {
        return WatehouseMaterialMapper.reunits();

    }

    //返回所有某一个仓库的所有某种材料
    @Override
    public List<PickCondition> selectMatById(HashMap<String, Object> map) {

        return WatehouseMaterialMapper.selectMatById(map);
    }

    //入库
    @Override
    public boolean watehousing(PickCondition pickCondition) {
        //先判断是不是已经有的材料
        int add=0;
        if (1!=WatehouseMaterialMapper.selectMatByMdId(pickCondition.getMdId())){
        //是一种新材料的话插入
         add = WatehouseMaterialMapper.addMat(pickCondition);
        }else {
            //添加数量
            Double num = pickCondition.getNum();
            double result=num+pickCondition.getPickNum();
            HashMap<String,Object> map=new HashMap<>();
            map.put("result",result);
            map.put("pickCondition",pickCondition);
           add= WatehouseMaterialMapper.addMatSum(map);
        }
        //插入一条仓库操作记录
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String now = simpleDateFormat.format(new Date());
        pickCondition.setCreateTime(now);
        int addProRecord = WatehouseMaterialMapper.addWareRecord(pickCondition);
        if (add == 1 && addProRecord == 1) {
            return true;
        } else {
            return false;
        }
    }

    //出库
    @Override
    public boolean outWatehouse(PickCondition pickCondition) throws Exception {

        //从仓库中减去数量
        //去仓库减去数量
        //获取材料总量
        double total = pickCondition.getNum();
        //获取材料领料量
        double pick = pickCondition.getPickNum();
        //需要修改的量
        double pickResultNum = total - pick;

        HashMap<String, Object> map = new HashMap();
        map.put("pickResultNum", pickResultNum);
        map.put("pickCondition", pickCondition);
        //前置校验查询数量是否足够
        int sum = WatehouseMaterialMapper.selectMaterialNum(map);
        if (pickResultNum>sum){
            throw new Exception("refresh the page,insufficient inventory");
        }
        //去仓库修改数量
        int update = WatehouseMaterialMapper.updateSum(map);

        //判断是否去了一个项目
        boolean a = false;
        int insertProMat = 0;
        int addProRecord = 0;
        String wrWhereabouts = pickCondition.getWrWhereabouts();
        List<String> reproname = WatehouseMaterialMapper.reproname();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String now = simpleDateFormat.format(new Date());
        pickCondition.setCreateTime(now);
        for (int i = 0; i < reproname.size(); i++) {
            if (reproname.get(i).equals(wrWhereabouts)) {
                //去向与项目名字相同
                //再判断项目材料中是都有这个材料大类
                //如果没有这个大类
                HashMap<String, Object> map1 = new HashMap<>();
                map1.put("mId", pickCondition.getmId());
                map1.put("pname", wrWhereabouts);
                if (null == WatehouseMaterialMapper.selectMid(map1)) {
                    //查询项目中是否有一个材料的大类 没有的话插入一个大类
                    //根据项目名字查项目id
                    Long pId = WatehouseMaterialMapper.selectpIdByPname(wrWhereabouts);
                    map1.put("pId", pId);
                    WatehouseMaterialMapper.insertProMat(map1);

                }
//                去项目材料中添加材料
                insertProMat = WatehouseMaterialMapper.insertMaterialByCondition(pickCondition);
                //去项目操作记录中加一条操作记录
                addProRecord = WatehouseMaterialMapper.insertPickRecord(pickCondition);
                a = true;

            }
        }
        //去仓库插入一条操作记录
        int addWareRecord = WatehouseMaterialMapper.addWareRecord(pickCondition);
        if (a) {
            if (update == 1 && insertProMat == 1 && addProRecord == 1 && addWareRecord == 1) {
                return true;
            } else {
                return false;
            }
        } else {
            if (update == 1 && addWareRecord == 1) {
                return true;
            } else {
                return false;
            }
        }


    }

    //返回所有项目的名字
    @Override
    public List<String> reproname() {
        return WatehouseMaterialMapper.reproname();
    }

    @Override
    public List<MaterialThree> queryMaterialList(MaterialThree MaterialThree) {
        return WatehouseMaterialMapper.queryMaterialList(MaterialThree);
    }

    /**
     * 模版多sheet导出示例
     * @return
     */
    public Workbook exportMoreSheetByTemplate(String date) throws IOException {
        List<Map> list1 = WatehouseMaterialMapper.inStorageAForMaterial(date);
        List<Map> list2 = WatehouseMaterialMapper.inStorageBForMaterial(date);
        List<Map> list3 = Lists.newArrayList();
        Double sum = 0.0;
        // sheet1内容
        for (int i = 0; i <list1.size() ; i++) {
            Double price=Double.valueOf(list1.get(i).get("md_price")+"");
            Double number=Double.valueOf(list1.get(i).get("wr_number")+"");
            sum+=price*number;
        }
        Map<String,Object> map1 = new HashMap<String, Object>() ;
        map1.put("data",list1) ;
        map1.put("sum",sum);
        // sheet2内容
        double sum1=0.0;
        for (int i = 0; i <list2.size() ; i++) {
            Double price=Double.valueOf(list2.get(i).get("md_price")+"");
            Double number=Double.valueOf(list2.get(i).get("wr_number")+"");
            sum1+=price*number;
        }
        map1.put("data1",list2) ;
        map1.put("sum1",sum1);

        // 设置导出配置
        // 获取导出excel指定模版

        TemplateExportParams params = new TemplateExportParams("/home/ruoyi/excel/入库.xlsx",true);
        // 导出excel
        return ExcelExportUtil.exportExcel(params , map1 );
    }
    /**
     * 模版多sheet导出示例
     * @return
     */
    public Workbook exportByTemplate(String date) throws IOException {
        List<Map> list1 = WatehouseMaterialMapper.outStorageAForMaterial(date);
        List<Map> list2 = WatehouseMaterialMapper.outStorageBForMaterial(date);
        List<Map> list3 = Lists.newArrayList();
        Double sum = 0.0;
        // sheet1内容
        for (int i = 0; i <list1.size() ; i++) {
            Double price=Double.valueOf(list1.get(i).get("md_price")+"");
            Double number=Double.valueOf(list1.get(i).get("wr_number")+"");
            sum+=price*number;
        }
        Map<String,Object> map1 = new HashMap<String, Object>() ;
        map1.put("data",list1) ;
        map1.put("sum",sum);
        // sheet2内容
        double sum1=0.0;
        for (int i = 0; i <list2.size() ; i++) {
            Double price=Double.valueOf(list2.get(i).get("md_price")+"");
            Double number=Double.valueOf(list2.get(i).get("wr_number")+"");
            sum1+=price*number;
        }
        map1.put("data1",list2) ;
        map1.put("sum1",sum1);

        // 设置导出配置
        // 获取导出excel指定模版

        TemplateExportParams params = new TemplateExportParams("/home/ruoyi/excel/出库.xlsx",true);
        // 导出excel
        return ExcelExportUtil.exportExcel(params , map1 );
    }
    public   void upload(){
        System.out.println("进来了");
        FileOutputStream out = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        //当前月份
        String time = df.format(new Date());
        try {
            //月份减一
            Date date = df.parse(time);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.MONTH, -1);
            //上个月
            String format = df.format(calendar.getTime());
            List<Map> maps = WatehouseMaterialMapper.endexpectMaterial();
            Double sumMoney = WatehouseMaterialMapper.querySumMoney();
            Double sum = 0.00;
            DecimalFormat decimalFormat = new DecimalFormat("######0.00");
            decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
            for (int i = 0; i < maps.size(); i++) {
                maps.get(i).put("id", i + 1);
            }

            // 表格使用的数据
            Map map = new HashMap();
            map.put("data", maps);//放入表一数据
            map.put("date", format);//放入表一数据
            map.put("sum",decimalFormat.format(new BigDecimal(sumMoney.toString())));//放入表一数据
            format += ".xlsx";
            TemplateExportParams params = new TemplateExportParams("C:\\Users\\Administrator\\Desktop\\期末材料.xlsx");
            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
            out = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\恒南二号仓库.xlsx" );
            workbook.write(out);
            File file1 = new File("C:\\Users\\Administrator\\Desktop\\恒南二号仓库.xlsx");
//            QiniuCloudUtil.upload(file1, format);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
    }
}
